/*
 * This file is part of aion-engine <aion-engine.com>
 *
 * aion-engine is private software: you can redistribute it and or modify
 * it under the terms of the GNU Lesser Public License as published by
 * the Private Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * aion-engine is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser Public License for more details.
 *
 * You should have received a copy of the GNU Lesser Public License
 * along with aion-engine.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.aionengine.gameserver.world.zone;

import com.aionengine.gameserver.model.gameobjects.Creature;
import com.aionengine.gameserver.model.gameobjects.player.Player;
import com.aionengine.gameserver.model.templates.zone.ZoneInfo;
import com.aionengine.gameserver.world.knownlist.Visitor;
import javolution.util.FastMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author MrPoke
 */
public class SiegeZoneInstance extends ZoneInstance {

    private static final Logger log = LoggerFactory.getLogger(SiegeZoneInstance.class);

    private FastMap<Integer, Player> players = new FastMap<Integer, Player>();

    /**
     * @param mapId
     * @param template
     * @param handler
     */
    public SiegeZoneInstance(int mapId, ZoneInfo template) {
        super(mapId, template);
    }

    @Override
    public boolean onEnter(Creature creature) {
        if (super.onEnter(creature)) {
            if (creature instanceof Player)
                players.put(creature.getObjectId(), (Player) creature);
            return true;
        }
        return false;
    }

    @Override
    public synchronized boolean onLeave(Creature creature) {
        if (super.onLeave(creature)) {
            if (creature instanceof Player)
                players.remove(creature.getObjectId());
            return true;
        }
        return false;
    }

    public void doOnAllPlayers(Visitor<Player> visitor) {
        try {
            for (FastMap.Entry<Integer, Player> e = players.head(), mapEnd = players.tail(); (e = e.getNext()) != mapEnd; ) {
                Player player = e.getValue();
                if (player != null) {
                    visitor.visit(player);
                }
            }
        } catch (Exception ex) {
            log.error("Exception when running visitor on all players" + ex);
        }
    }
}
